package gateway.route;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.json.JSONUtil;
import gateway.pojo.JsonRootBean;
import gateway.pojo.PrometheusResult;
import gateway.pojo.SS;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.util.CollectionUtils;

import java.io.IOException;

public class PrometheusResultParserDemo {

    public static void parsePrometheusQueryResult(String jsonResponse) {
        try {
            // 解析 JSON 字符串
            JSONObject jsonObject = new JSONObject(jsonResponse);

            // 检查状态是否成功
            String status = jsonObject.getString("status");
            if (!"success".equals(status)) {
                System.err.println("Query failed: " + jsonObject.getString("error"));
                return;
            }

            // 获取数据类型（例如 "matrix" 或 "vector"）
            String resultType = jsonObject.getJSONObject("data").getString("resultType");
            System.out.println("Result type: " + resultType);

            // 获取结果数组
            JSONArray resultArray = jsonObject.getJSONObject("data").getJSONArray("result");

            // 遍历结果数组并解析每个元素（取决于 resultType，可能是矩阵或向量）
            for (int i = 0; i < resultArray.length(); i++) {
                JSONObject resultObj = resultArray.getJSONObject(i);

                // 如果 resultType 是 "vector"，则解析指标名和样本值
                if ("vector".equals(resultType)) {
                    String metricName = resultObj.getString("metric").toString();
                    String value = resultObj.getString("value").split(" ")[1]; // 假设值是 "123.456 1609459200" 这样的格式
                    System.out.println("Metric name: " + metricName + ", Value: " + value);
                }
                // 如果 resultType 是 "matrix"，则需要进一步解析每个时间点上的样本值
                // ...
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // 假设 jsonResponse 是从 Prometheus 查询 API 获取的 JSON 响应字符串
        //String jsonResponse = "{\"status\":\"success\",\"data\":{\"resultType\":\"vector\",\"result\":[{\"metric\":{\"__name__\":\"up\",\"instance\":\"localhost:9090\",\"job\":\"prometheus\"},\"value\":[1,\"1609459200000\"]},{\"metric\":{\"__name__\":\"another_metric\",\"job\":\"some_job\"},\"value\":[2,\"1609459201000\"]}]}}";
        //parsePrometheusQueryResult(jsonResponse);


        Request request = new Request.Builder()
                .url("http://localhost:9090/api/v1/query?query=batchjob1_user_counter&time=1715497302.211")
                .get()
                .build();
        OkHttpClient client = new OkHttpClient();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            // 打印响应内容，通常 Pushgateway 会返回一个空响应体或简单的确认消息
            String res = response.body().string() ;
            System.out.println(res);

            JsonRootBean<PrometheusResult> bean = JSONUtil.toBean(res, new TypeReference<JsonRootBean<PrometheusResult>>() {
            }, true);
            System.out.println(bean);
            if(!"success".equals(bean.getStatus())){
                return;
            }
            PrometheusResult data = bean.getData();
            if(data==null||CollectionUtils.isEmpty(data.getResult())){
                return;
            }
            for (SS ss : data.getResult()) {
                System.out.println(ss);
                PrometheusPushgatewayDemo.pushData(ss.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}